"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 备机事务数据持久性测试
Create At   : 2023/07/19
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.创建测试表
    3.备机开启事务表1插入数据提交，删除表2数据回滚
    4.重启集群
    5.新主（原备）查询表数据
    6.清理环境
Expect      :
    1.修改成功
    2.成功
    3.执行成功
    4.成功
    5.表1两条数据，表2 10条数据
    6.成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_sh = CommonSH('Standby1DbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table1 = 't_multi_node_write_0069_1'
        self.table2 = 't_multi_node_write_0069_2'
        self.enable_remote_execute = 'enable_remote_execute'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.log.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')

        step2 = "-----step2:创建测试表;expect:成功-----"
        self.log.info(step2)
        sql_msg = self.standby_sh.execut_db_sql(
            f'''drop table if exists {self.table1}, {self.table2} cascade;
            create table {self.table1}(col1 int, col2 int) with(segment=on);
            create table {self.table2} with(segment=on) as 
             select generate_series(1,10) col1;''')
        self.log.info(sql_msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(5)

        step3 = "-----step3:备机开启事务，表中插入数据，查询;expect:执行成功,两条数据-----"
        self.log.info(step3)
        sql = f'''begin;
        insert into {self.table1} values(1, 2),(2, 3);
        select * from {self.table1} order by 1;
        end;
        start transaction;
        delete from {self.table2};
        rollback;'''
        self.log.info(sql)
        sql_res = self.standby_sh.execut_db_sql(sql)
        self.log.info(sql_res)
        self.assertIn('BEGIN', sql_res, f"执行失败: {step3}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, sql_res,
                      f"执行失败: {step3}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, sql_res,
                      f"执行失败:{step3}")
        self.assertIn(self.constant.ROLLBACK_MSG, sql_res, f"执行失败:{step3}")

        step4 = "-----step4:重启集群;expect:成功-----"
        self.log.info(step4)
        cmd = f"source {macro.DB_ENV_PATH};cm_ctl stop && cm_ctl start"
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn('stop cluster successfully', res, f"执行失败: {step4}")
        self.assertIn('start cluster successfully', res, f"执行失败: {step4}")

        step5 = "-----step5:新主（原备）查询表数据;expect:表1两条数据，表2 10条数据-----"
        self.log.info(step5)
        sql_msg = self.standby_sh.execut_db_sql(
            f"select * from {self.table1};"
            f"select * from {self.table2};")
        self.log.info(sql_msg)
        self.assertIn('1 |    2', sql_msg, f'执行失败:{step5}')
        self.assertIn('2 |    3', sql_msg, f'执行失败:{step5}')
        self.assertIn('10 rows', sql_msg, f'执行失败:{step5}')

    def tearDown(self):
        step6 = "-----step6:恢复参数;expect:恢复参数成功-----"
        self.log.info(step6)
        drop_res = self.standby_sh.execut_db_sql(
            f'drop table if exists {self.table1},{self.table2} cascade;')
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEqual(self.constant.DROP_TABLE_SUCCESS, drop_res,
                         f'执行失败:{step6}')
        self.assertTrue(result1, f'执行失败:{step6}')
        self.assertTrue(restart_res, f'执行失败:{step6}')
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step6}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
